import {
	domain
} from '../config';
import {
	showToast,
	showModal
} from '@/utils/util.js'
import * as store from '../store/index'
import {
	stringify
} from 'qs';

let retryCount = 0;
let queue = [];
let busy = false;
export let session = uni.getStorageSync('session') || {
	token: '',
	expire_time: 0,
	openid: '',
	session_key: '',
	phone: '',
	userInfo: {}
};

export let getToken = (params = {}) => {
	params = {
		...params,
		UserName: 'hic',
		Password: 'hic@123'
	}
	uni.request({
		url: domain + '/Token/GetToken',
		method: 'POST',
		data: params,
		header: {
			'content-type': 'application/json',
			'x-app-platform': 'wx'
		},
		success: function(res) {
			//获取 token expire_time
			const {
				Token,
				Timeout
			} = res.data;
			session.token = Token;
			session.expire_time = Date.now() + 60 * 60 * Timeout * 1000;
			uni.setStorage({
				key: 'session',
				data: session
			})
			if (queue) {
				queue.forEach(x => x());
			}
			queue = [];
			retryCount = 0;
			// callback && callback(true)
		},
		fail: function(res) {

		},
		complete: function() {}
	})
}

//普通登录、手机号登录
export let login = (params = {}, {  //  login=( params = {},{callback}={}    )=>{}
	callback
} = {}) => {
	retryCount++; //retryCount为0
	busy = true;
	uni.login({
		success: (res) => {
			let url = domain + '/uni/GetJscode2session';
			const {
				method,
				...param
			} = params;
			if (param.iv) {
				url = domain + '/uni/GetPhoneNumber';
			}
			uni.request({
				url,
				data: {
					js_code: res.code,
					...param
				},
				method: method || 'POST',
				header: {
					'content-type': 'application/json',
					'x-app-platform': 'wx'
				},
				success: function(res) {
					if (!res.data) {
						return retryCount <= 3 ? login() : console.error('登录重试3次后失败');
					}
					const {
						OpenID,
						Phone,
						Session_Key,
						openid,
						session_key,
					} = res.data.Data;
					const userInfo = res.data.Data.userInfo || {}
					session.openid = OpenID || openid || userInfo.OpenID;
					session.session_key = Session_Key || session_key;
					session.phone = Phone || userInfo.Phone;
					//手动设置有效时间：1个小时
					// session.expire_time = Date.now() + 60*60* 1000;

					if(userInfo){
						session.userInfo  = userInfo;
						store.default.commit('uni/SET_USERINFO', userInfo)
						callback && callback(userInfo)
					}else{
						callback && callback({})

					}
					uni.setStorage({
						key: 'session',
						data: session
					})
					if (queue) {
						queue.forEach(x => x());
					}
					queue = [];
					retryCount = 0;

				},
				fail: function(res) {
					if (retryCount <= 3) {

						login(params,{callback}={});
					}else{
						callback({});

					}
				},
				complete: function() {
					busy = false;
				}
			})
		}
	})
};
/* let params = {
		url: newUrl,
		data: newData,
		method,
	}; */
	
export let request = (params) => {  	
	//console.log('request=====params',params)
	const whiteUrl = params.url.indexOf('/uni/Config') > -1
	//console.log('url======',whiteUrl)
	if (session.token && session.expire_time > Date.now() || whiteUrl) {
		return uni.request({
			...params,
			header: {
				...params.header,
				"auth": session.token
			},
			
			success: res => {
				
				if (res.statusCode == 401) {
					queue.push(() => request(params));
					getToken(); //去检查登录
				} else if (res.statusCode == 200) {
					//排除直接返回数组的数据（通用接口）
					if (res.data && res.data instanceof Array) {
						params.success && params.success(res);
					} else {
						if (res.data.Code === 0||res.data.Code === 20000) {
							params.success && params.success(res);
						} else {
							params.fail && params.fail(res)
							showModal({
								content: res.data && res.data.Message ? res.data.Message : ''
							})
						}
					}
				} else {
					params.fail && params.fail(res)
					showModal({
						content: res.data && res.data.Message ? res.data.Message : ''
					})
				}
			}
		});
	} else {
		queue.push(() => request(params));
		if (!busy) {
			getToken();
		}
	}
};
//let domain='https://anhui.hichain.com/WebAPI/api';
export let wxRequest = (url, data, method = 'GET') => {
	return new Promise(function(resolve, reject) {
		let newUrl = domain + '/' + url;
		const {
			query,
			...newData
		} = data;

		if (method == 'GET' || method == 'DELETE' || query) {
			newUrl = `${domain}/${url}?${stringify(newData)}`;
		}
		let params = {
			url: newUrl,
			data: newData,
			method,
		};

		params.success = function(res) {
			resolve(res.data);
		}

		params.fail = function(res) {
			reject(res);
		}

		request(params);
	});
};

export let uploadFile = params => {
	
	return new Promise((reslove, reject) => {
		params.url = domain + params.url || 'attachment/upload';
		if (!params.name) {
			params.name = 'file';
		}
		// params.header = { ...params.header,
		// 	"x-access-token": session.token
		// };
		params.header = { ...params.header,
			"auth": session.token
		};
		
		wx.uploadFile({
			...params,
			success: res => {
				
				if (res.statusCode === 200) {
					if (res.data) {
						// const newData = res.data.replace(/("|')/g, "");
						let newData=res.data
						// console.log('request--res==',newData,res)
						let _newData=JSON.parse(newData)
						reslove(_newData);
					}
				} else {
					showToast({
						title: '上传失败,重试',
						// image: '../../static/img/fail.png',
						duration: 3000
					})
				}
			},
		})

	})

}

export let moduleGenerator = (module, actionList) => {
	let state = {},
		mutations = {},
		actions = {};
	actionList.forEach(config => {
		let actionName = typeof config === 'string' ? config : config.action;
		let url = actionName;
		let mutationName = 'SET_' + actionName.toUpperCase();
		if (config.method === 'GET') {
			state[actionName] = config.state || [];
		}
		actions[actionName] = ({
			commit
		}, params = {}) => {
			return new Promise((resolve, reject) => {
				const {
					onlyField,
					...param
				} = params;
				wxRequest('uni/' + url, onlyField ? params.payload : param, config.method).then(res => {
					resolve(res);
					if (config.method === 'GET') commit(mutationName, res);
					config.callback && config.callback(commit);
				}).catch(reject)
			})
		}
		mutations[mutationName] = (state, value) => {
			state[actionName] = value;
		};
	});
	return {
		state,
		mutations,
		actions
	};
}
